# tasks.py
from .models import*
from .flylu.flyluAM import *
from .flylu.util.Util import *
from .celery import app
@app.task(bind=True,name='小说发布')
def my_periodic_task(self,book_name,chapters_per_day,chapters_per_all):
    fly_config =  FlyConfig.objects.get(bookName=book_name)
    if fly_config:
        flylu =  FlyLu()
        bookName = getattr(fly_config, 'bookName')
        relessesUrl = getattr(fly_config, 'relessesUrl')
        proxyHost = getattr(fly_config,'proxyHost')
        proxyPort = getattr(fly_config,'proxyPort')
        proxyUser = getattr(fly_config,'proxyUser')
        proxyPass = getattr(fly_config,'proxyPass')
        pluginPath = getattr(fly_config,'pluginPath')
        wordPath = getattr(fly_config, 'wordPath')
        startPar = getattr(fly_config, 'startPar')
        endPar = getattr(fly_config, 'endPar')
        selectFlag = getattr(fly_config, 'selectFlag')
        currentChapter = getattr(fly_config, 'currentChapter')
        # 获取外键关联的实例
        related_obj = fly_config.userName
        userName = getattr(related_obj, 'userName')
        passWord = getattr(related_obj, 'passWord')
        print({'bookName':bookName,'relessesUrl':relessesUrl,'wordPath':wordPath,
            'startPar':startPar,'endPar':endPar,'selectFlag':selectFlag,'currentChapter':currentChapter,
            'userName':userName,'passWord':passWord})
        # 当前章节小于等于word中最大章节
        if currentChapter <= chapters_per_all:
            # word中包含每天要发布的chapters_per_day章节数量
            if (currentChapter+chapters_per_day)<chapters_per_all:
                # 计算结束的章节
                end_chapter =  currentChapter+chapters_per_day-1
                # 当前开始的章节
                current_chapter_str = Util.conversionString(currentChapter)
                # 结束的章节
                end_chapter_str = Util.conversionString(end_chapter)
                flylu.add_article(relessesUrl,proxyHost,proxyPort,proxyUser,proxyPass,pluginPath,userName,passWord,wordPath,current_chapter_str,end_chapter_str,selectFlag)
                # 将本次结束的章节存储到数据库
                fly_config.currentChapter = end_chapter+1
                fly_config.save()
                print("一次周期章节发布完成！")
            else:
                # 当前开始的章节
                current_chapter_str = Util.conversionString(currentChapter)
                flylu.add_article(relessesUrl,proxyHost,proxyPort,proxyUser,proxyPass,pluginPath,userName,passWord,wordPath,current_chapter_str,endPar,selectFlag)
                # 将本次结束的章节存储到数据库
                fly_config.currentChapter = Util.chinese_to_int(endPar)+1
                fly_config.save()
            return True
        else:
            print("周期预定章节发布完成！")
            return True
         
    else:
        # 如果没有找到记录，可以执行其他操作
        print("没有找到匹配的记录。")
        return False

        